package cms

import (
	kinit "longblog/work/base/initialize"
	kmodel "longblog/work/model"
	"bytes"
	"fmt"
	"time"

	jgorm "github.com/jinzhu/gorm"
)

func init() {

}

func InsertCmsAdminUsers(tx *jgorm.DB, name string, password string, avatar string, loginIp string) (kmodel.CmsAdminUsers, error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	insertTime := time.Now().Format("2006-01-02 15:04:05")
	obj := kmodel.CmsAdminUsers{
		Name:      name,
		Password:  password,
		Avatar:    avatar,
		LoginIp:   loginIp,
		CreatedAt: insertTime,
		LoginAt:   insertTime,
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func GetCmsAdminUsers(tx *jgorm.DB, name string) []kmodel.CmsAdminUsers {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []kmodel.CmsAdminUsers
	if name != "" {
		tx.Where("name=?", name).Find(&objs)
	} else {
		tx.Find(&objs)
	}
	return objs
}

func GetCmsAdminUsersById(tx *jgorm.DB, id int64) kmodel.CmsAdminUsers {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminUsers
	tx.Where("id=? ", id).First(&objs)
	return objs
}
func GetCmsAdminUsersByName(tx *jgorm.DB, name string) kmodel.CmsAdminUsers {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminUsers
	tx.Where("name=? ", name).First(&objs)
	return objs
}

func UpdateCmsAdminUsersPicById(tx *jgorm.DB, id int64, avatar string) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(kmodel.CmsAdminUsers{}).Where("id=?", id).Updates(map[string]interface{}{"avatar": avatar}).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func UpdateCmsAdminUsersById(tx *jgorm.DB, id int64, password string) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(kmodel.CmsAdminUsers{}).Where("id=?", id).Updates(map[string]interface{}{"password": password}).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func UpdateCmsAdminUsersAllById(tx *jgorm.DB, id int64, name string, password string) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	data := map[string]interface{}{
		"name": name,
	}
	if password != "" {
		data["password"] = password
	}
	if err := tx.Model(kmodel.CmsAdminUsers{}).Where("id=?", id).Updates(data).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func UpdateCmsAdminUsersLoginInfoById(tx *jgorm.DB, id int64, ip string) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(kmodel.CmsAdminUsers{}).Where("id=?", id).Updates(map[string]interface{}{"login_ip": ip, "login_at": time.Now().Format("2006-01-02 15:04:05")}).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsAdminUsersById(tx *jgorm.DB, id int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminUsers
	if err := tx.Where("id=? ", id).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

//---------------------------------------------------------------------------------------

func InsertCmsAdminRoles(tx *jgorm.DB, name string) (kmodel.CmsAdminRoles, error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	insertTime := time.Now().Format("2006-01-02 15:04:05")
	obj := kmodel.CmsAdminRoles{
		Name:      name,
		CreatedAt: insertTime,
		UpdatedAt: insertTime,
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func GetCmsAdminRoles(tx *jgorm.DB) []kmodel.CmsAdminRoles {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []kmodel.CmsAdminRoles
	tx.Find(&objs)
	return objs
}

func GetCmsAdminRolesById(tx *jgorm.DB, id int64) kmodel.CmsAdminRoles {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminRoles
	tx.Where("id=? ", id).First(&objs)
	return objs
}
func GetCmsAdminRolesByName(tx *jgorm.DB, name string) kmodel.CmsAdminRoles {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminRoles
	tx.Where("name=? ", name).First(&objs)
	return objs
}

func UpdateCmsAdminRolesById(tx *jgorm.DB, id int64, name string) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(kmodel.CmsAdminRoles{}).Where("id=?", id).Updates(map[string]interface{}{"name": name, "updated_at": time.Now().Format("2006-01-02 15:04:05")}).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsAdminRolesById(tx *jgorm.DB, id int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminRoles
	if err := tx.Where("id=? ", id).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

//---------------------------------------------------------------------------------------

func InsertCmsAdminPermissions(tx *jgorm.DB, name string, pid int64, path string, isShow int64) (kmodel.CmsAdminPermissions, error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	insertTime := time.Now().Format("2006-01-02 15:04:05")
	obj := kmodel.CmsAdminPermissions{
		Name:      name,
		Pid:       pid,
		Path:      path,
		IsShow:    isShow,
		CreatedAt: insertTime,
		UpdatedAt: insertTime,
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func GetCmsAdminPermissions(tx *jgorm.DB) []kmodel.CmsAdminPermissions {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []kmodel.CmsAdminPermissions
	tx.Find(&objs)
	return objs
}

func GetCmsAdminPermissionsById(tx *jgorm.DB, id int64) kmodel.CmsAdminPermissions {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminPermissions
	tx.Where("id=? ", id).First(&objs)
	return objs
}
func GetCmsAdminPermissionsByName(tx *jgorm.DB, name string) kmodel.CmsAdminPermissions {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminPermissions
	tx.Where("name=? ", name).First(&objs)
	return objs
}
func GetCmsAdminPermissionsByNamePidPath(tx *jgorm.DB,name string,pid int64, path string) kmodel.CmsAdminPermissions {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminPermissions
	tx.Where("name=? and pid=? and path=?",name, pid,path).First(&objs)
	return objs
}


func GetCmsAdminPermissionsByPath(tx *jgorm.DB, path string) kmodel.CmsAdminPermissions {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminPermissions
	tx.Where("path=? ", path).First(&objs)
	return objs
}

func UpdateCmsAdminPermissionsById(tx *jgorm.DB, id int64, name string, pid int64, path string, isShow int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(kmodel.CmsAdminPermissions{}).Where("id=?", id).Updates(map[string]interface{}{"name": name, "pid": pid, "path": path, "is_show": isShow, "updated_at": time.Now().Format("2006-01-02 15:04:05")}).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsAdminPermissionsById(tx *jgorm.DB, ids []int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminPermissions
	if err := tx.Where("id in (?) ", ids).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

//---------------------------------------------------------------------------------------

func InsertCmsAdminRoleHasPermissionsByRaw(tx *jgorm.DB, roleId int64, permissionId []int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	insertTime := time.Now().Format("2006-01-02 15:04:05")
	sql := "insert into `cms_admin_role_has_permissions` (`role_id`,`permission_id`,`created_at`) values "

	var buffer bytes.Buffer
	buffer.WriteString(sql)
	for k, v := range permissionId {
		if len(permissionId)-1 == k {
			buffer.WriteString(fmt.Sprintf("(%d, %d, '%s');", roleId, v, insertTime))
		} else {
			buffer.WriteString(fmt.Sprintf("(%d, %d, '%s'),", roleId, v, insertTime))
		}
	}
	return tx.Exec(buffer.String()).Error
}

func GetCmsAdminRoleHasPermissionsByRoleId(tx *jgorm.DB, roleId int64) map[int64]kmodel.CmsAdminRoleHasPermissions {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []kmodel.CmsAdminRoleHasPermissions
	var dict map[int64]kmodel.CmsAdminRoleHasPermissions
	tx.Where("role_id=? ", roleId).Find(&objs)
	dict = make(map[int64]kmodel.CmsAdminRoleHasPermissions)
	count := len(objs)
	for i := 0; i < count; i++ {
		dict[objs[i].PermissionId] = objs[i]
	}
	return dict
}

func DelCmsAdminRoleHasPermissionsByRolePermissionId(tx *jgorm.DB, roleId int64, ids []int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminRoleHasPermissions
	if err := tx.Where("role_id=? ", roleId).Where("permission_id in (?) ", ids).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsAdminRoleHasPermissionsByRoleId(tx *jgorm.DB, roleId int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminRoleHasPermissions
	if err := tx.Where("role_id=? ", roleId).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsAdminRoleHasPermissionsByPermissionId(tx *jgorm.DB, ids []int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminRoleHasPermissions
	if err := tx.Where("permission_id in (?) ", ids).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

//---------------------------------------------------------------------------------------

func InsertCmsAdminUserHasRoles(tx *jgorm.DB, adminId int64, roleId int64) (kmodel.CmsAdminUserHasRoles, error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	obj := kmodel.CmsAdminUserHasRoles{
		AdminId:   adminId,
		RoleId:    roleId,
		CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func GetCmsAdminUserHasRolesByAdminId(tx *jgorm.DB, adminId int64) kmodel.CmsAdminUserHasRoles {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminUserHasRoles
	tx.Where("admin_id=? ", adminId).First(&objs)
	return objs
}

func UpdateCmsAdminUserHasRolesByAdminId(tx *jgorm.DB, adminId int64, roleId int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(kmodel.CmsAdminUserHasRoles{}).Where("admin_id=?", adminId).Updates(map[string]interface{}{"role_id": roleId}).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsAdminUserHasRolesByRoleId(tx *jgorm.DB, roleId int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminUserHasRoles
	if err := tx.Where("role_id=? ", roleId).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsAdminUserHasRolesByAdminId(tx *jgorm.DB, adminId int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminUserHasRoles
	if err := tx.Where("admin_id=? ", adminId).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

//---------------------------------------------------------------------------------------

func GetCmsAdminRoleHasPermissionsByRaw(tx *jgorm.DB, path string) []kmodel.RoleIdBlock {
	if tx == nil {
		tx = kinit.Gorm
	}
	var ids []kmodel.RoleIdBlock
	sql := "select role_id from `cms_admin_permissions` as ap right join " +
		"`cms_admin_role_has_permissions` as p on p.permission_id=ap.id where"
	sql += fmt.Sprintf(" ap.path = '%s'; ", path)

	tx.Raw(sql).Scan(&ids)
	return ids
}

func GetCmsAdminRoleIdHasPermissionsByRaw(tx *jgorm.DB, roleId int64) []kmodel.CmsAdminPermissions {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []kmodel.CmsAdminPermissions
	sql := "select * from `cms_admin_permissions` where is_show = ? and id in (" +
		"select permission_id from `cms_admin_role_has_permissions` where role_id = ?); "

	tx.Raw(sql, 1, roleId).Scan(&objs)
	return objs
}

func GetCmsAdminUserHasRoleByRaw(tx *jgorm.DB, userId int64) kmodel.RoleIdBlock {
	if tx == nil {
		tx = kinit.Gorm
	}
	var id kmodel.RoleIdBlock
	sql := "select role_id from `cms_admin_users` as u left join " +
		"`cms_admin_user_has_roles` as r on u.id=r.admin_id where "
	sql += fmt.Sprintf(" u.id = %d; ", userId)

	tx.Raw(sql).Scan(&id)
	return id
}

//---------------------------------------------------------------------------------------

func InsertCmsAdminOptionLog(tx *jgorm.DB, userName string, userId int64, path string, method string, option string) (kmodel.CmsAdminOptionLog, error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	obj := kmodel.CmsAdminOptionLog{
		UserName:  userName,
		UserId:    userId,
		Path:      path,
		Method:    method,
		Option:    option,
		CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func CountCmsAdminOptionLog(tx *jgorm.DB, userName string) int {
	if tx == nil {
		tx = kinit.Gorm
	}
	count := 0
	tx = tx.Model(kmodel.CmsAdminOptionLog{})
	if userName != "" {
		tx = tx.Where("user_name like ?", "%"+userName+"%")
	}
	tx.Count(&count)
	return count
}

func GetCmsAdminOptionLog(tx *jgorm.DB, userName string, page int64, pageSize int64) []kmodel.CmsAdminOptionLog {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []kmodel.CmsAdminOptionLog
	if userName != "" {
		tx = tx.Where("user_name like ?", "%"+userName+"%")
	}
	tx.Order("id desc").Limit(pageSize).Offset((page - 1) * pageSize).Find(&objs)
	return objs
}

func DelCmsAdminOptionLogByIds(tx *jgorm.DB, ids []int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsAdminOptionLog
	if err := tx.Where("id in (?) ", ids).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

//---------------------------------------------------------------------------------------

func InsertCmsBurstRecord(tx *jgorm.DB, uid int64, tempFolderName string, fileName string, fileTotalSize string, burstTotal int64) (kmodel.CmsBurstRecord, error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	obj := kmodel.CmsBurstRecord{
		Uid:            uid,
		TempFolderName: tempFolderName,
		FileName:       fileName,
		FileTotalSize:  fileTotalSize,
		BurstTotal:     burstTotal,
		CreatedAt:      time.Now().Format("2006-01-02 15:04:05"),
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func GetCmsBurstRecordByUidAndFilename(tx *jgorm.DB, uid int64, fileName string) kmodel.CmsBurstRecord {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsBurstRecord
	tx.Where("uid=? ", uid).Where("file_name = ?", fileName).First(&objs)
	return objs
}

func UpdateCmsBurstRecordById(tx *jgorm.DB, id int64, burstCount int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(kmodel.CmsBurstRecord{}).Where("id=?", id).Updates(map[string]interface{}{"burst_count": burstCount}).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

func DelCmsBurstRecordById(tx *jgorm.DB, id int64) error {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs kmodel.CmsBurstRecord
	if err := tx.Where("id = ? ", id).Delete(objs).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}

//---------------------------------------------------------------------------------------
